package keter.web.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfinal.kit.Prop;
import com.jfinal.kit.PropKit;

import keter.framework.util.SecurityUtil;

@WebFilter(filterName="csrfFilter",urlPatterns={"/*"})
public class CSRFFilter implements Filter {
	
    private static boolean enabled;

    /**
     * Logger for this class
     */
    private static final Logger logger = LoggerFactory.getLogger(CSRFFilter.class);

    /**允许链接转入的站点*/
    private String[] allowSites;
    
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {
    	HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if(!enabled){
        	chain.doFilter(request, response);
        }
        else{
       	String referer=request.getHeader("Referer"); 
//    	logger.error(referer);    	
       	logger.info("","");
      	if(StringUtils.isNotBlank(referer) && !StringUtils.containsAny(referer,allowSites)){
      		SecurityUtil.log("站点:["+referer+"]试图盗链，已被拦截!",SecurityUtil.EVENT_TYPE.CSRF);
      		return;
    	}
      		chain.doFilter(request, response);
        }
    }

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		Prop p = PropKit.use("keter-security.properties");
		enabled = p.getBoolean("csrf.enabled");
		allowSites = p.get("csrf.allow").split(",");
	}
	
    @Override
    public void destroy() {
    }

}
